package io.renren.modules.sys.model;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;

import javax.servlet.http.HttpServletResponse;


/**
 * POI动态导出EXCEL文档
 * 
 * @version v1.0
 * @param <T>
 *   应用泛型，代表任意一个符合javabean风格的类
 *   注意这里为了简单起见，boolean型的属性xxx的get器方式为getXxx(),而不是isXxx()
 *   byte[]表jpg格式的图片数据
 *  @author liupengfei
 */
public class SysUserExportExcel<T> {
//	public static final String FILE_SEPARATOR = System.getProperties().getProperty("file.separator");
	
	/**
	 * 
	 * @param sheetName
	 *            表格标题名
	 * @param headers
	 *            表格属性列名数组
	 * @param columnWidths
	 *            表格列的宽度数组
	 * @param dataset
	 *            需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的
	 *            javabean属性的数据类型有基本数据类型及String,Date,byte[](图片数据)
	 * @param response
	 *
	 *
	 */
	public void exportExcel(String sheetName,String[] headers,int[] columnWidths, Collection<T> dataset,
                            HttpServletResponse response) {
		exportExcel(sheetName, headers,columnWidths, dataset, response,"yyyy-MM-dd");
	}

	/**
	 * 这是一个通用的方法，利用了JAVA的反射机制，可以将放置在JAVA集合中并且符号一定条件的数据以EXCEL 的形式输出到指定IO设备上
	 * 
	 * @param title
	 *            表格标题名
	 * @param headers
	 *            表格属性列名数组
	 * @param columnWidths
	 *            表格列的宽度数组
	 * @param dataset
	 *            需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的
	 *            javabean属性的数据类型有基本数据类型及String,Date,byte[](图片数据)
	 * @param response
	 *
	 * @param pattern
	 *            如果有时间数据，设定输出格式。默认为"yyy-MM-dd"
	 */
	public void exportExcel(String title, String[] headers,int[] columnWidths,
			Collection<T> dataset, HttpServletResponse response, String pattern) {
		//声明一个工作薄
		HSSFWorkbook workbook = new HSSFWorkbook();
		// 生成一个表格
		HSSFSheet sheet = workbook.createSheet(title);
		//设置表格宽度
		for (int i = 0; i < columnWidths.length; i++) {
			sheet.setColumnWidth(i,columnWidths[i]);
		}
		
		//头部样式
		HSSFCellStyle styleHead = workbook.createCellStyle();
		styleHead.setAlignment(HorizontalAlignment.CENTER); //水平居中
		styleHead.setVerticalAlignment(VerticalAlignment.CENTER);// 垂直居中
		styleHead.setBorderBottom(BorderStyle.THIN); //下边框
		styleHead.setBorderLeft(BorderStyle.THIN);//左边框
		styleHead.setBorderTop(BorderStyle.THIN);//上边框
		styleHead.setBorderRight(BorderStyle.THIN);//右边框
		//头部字体
		HSSFFont fontHead = workbook.createFont();
		fontHead.setFontName("宋体");
		fontHead.setFontHeightInPoints((short) 20);
        fontHead.setBold(true);
		// 把字体应用到当前的样式
		styleHead.setFont(fontHead);
		
//		 标题样式
		HSSFCellStyle styleTitle = workbook.createCellStyle();
		styleTitle.setAlignment(HorizontalAlignment.CENTER);
		styleTitle.setVerticalAlignment(VerticalAlignment.CENTER);// 垂直居中
		styleTitle.setBorderBottom(BorderStyle.THIN); //下边框
		styleTitle.setBorderLeft(BorderStyle.THIN);//左边框
		styleTitle.setBorderTop(BorderStyle.THIN);//上边框
		styleTitle.setBorderRight(BorderStyle.THIN);//右边框
		//标题内容字体
		HSSFFont fontTitle = workbook.createFont();
		fontTitle.setFontName("宋体");
		fontTitle.setFontHeightInPoints((short) 16);
        fontTitle.setBold(true);
		//把字体应用到当前的样式
		styleTitle.setFont(fontTitle);
		
		//内容样式
		HSSFCellStyle styleContent = workbook.createCellStyle();
		styleContent.setAlignment(HorizontalAlignment.CENTER); //水平居中
		styleContent.setVerticalAlignment(VerticalAlignment.CENTER);// 垂直居中
		styleContent.setBorderBottom(BorderStyle.THIN); //下边框
		styleContent.setBorderLeft(BorderStyle.THIN);//左边框
		styleContent.setBorderTop(BorderStyle.THIN);//上边框
		styleContent.setBorderRight(BorderStyle.THIN);//右边框
		//内容字体
		HSSFFont fontContent = workbook.createFont();
		fontContent.setFontName("宋体");
		fontContent.setFontHeightInPoints((short) 14);
		//把字体应用到当前的样式
		styleContent.setFont(fontContent);
		
		
		//头部文字及合并
		HSSFRow row = sheet.createRow(0);
		sheet.addMergedRegion(new CellRangeAddress(0,0,0,headers.length-1));
		HSSFCell cellHead = row.createCell(0);
		cellHead.setCellStyle(styleHead);  //样式
		cellHead.setCellValue(title);
		// 产生表格标题行
		row = sheet.createRow(1);
		for (int i = 0; i < headers.length; i++) {
			HSSFCell cell = row.createCell(i);
			//设置标题样式
			cell.setCellStyle(styleTitle);
			HSSFRichTextString text = new HSSFRichTextString(headers[i]);
			cell.setCellValue(text);
		}
		
		//遍历集合数据，产生数据行
		Iterator<T> it = dataset.iterator(); 
		int index = 1;
		while (it.hasNext()) {
			index++;
			row = sheet.createRow(index);
			T t = (T) it.next();
			// 利用反射，根据javabean属性的先后顺序，动态调用getXxx()方法得到属性值
			Field[] fields = t.getClass().getDeclaredFields();
			for (int i = 0; i < fields.length; i++) {
				HSSFCell cell = row.createCell(i);

				Field field = fields[i];
				String fieldName = field.getName();
				String getMethodName = "get"
						+ fieldName.substring(0, 1).toUpperCase()
						+ fieldName.substring(1);
				try {
					Class<? extends Object> tCls = t.getClass();
					Method getMethod = tCls.getMethod(getMethodName,new Class[] {});
					Object value = getMethod.invoke(t, new Object[] {});
					// 判断值的类型后进行强制类型转换
					String textValue = "";
					if (value instanceof Date) {
						Date date = (Date) value;
						SimpleDateFormat sdf = new SimpleDateFormat(pattern);
						textValue = sdf.format(date);
					}else if (value !=null) {
						// 其它数据类型都当作字符串简单处理
						textValue = value.toString();
					}
					 //System.err.println("内容："+textValue);
					 
					//判断是否数字
					if (textValue != null && !"".equals(textValue)) {
						if (isNumber(textValue)) {
							// 是数字当作double处理
							cell.setCellValue(Double.parseDouble(textValue));
						} else {
							cell.setCellValue(textValue);
						}
					}
					//设置内容样式
					cell.setCellStyle(styleContent);
					
					
				} catch (SecurityException e) {
					e.printStackTrace();
				} catch (NoSuchMethodException e) {
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				} finally {
					// 清理资源
				}
			}
		}
		try {
            OutputStream os = response.getOutputStream();  // 取得输出流
            String codedfilename = URLEncoder.encode(title, "UTF-8");   //防止文件名中文乱码
            response.setHeader("Content-Disposition", "attachment;filename=" + codedfilename+".xls");  // 设定输出文件头
            response.setContentType("application/msexcel");// 定义输出类型
            workbook.write(os);
            os.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 判断字符串是否是数字
	 */
	public  boolean isNumber(String value) {
		return isInteger(value) || isDouble(value);
	}

	/**
	 * 判断字符串是否是浮点数
	 */
	public boolean isDouble(String value) {
		try {
			Double.parseDouble(value);
			if (value.contains("."))
				return true;
			return false;
		} catch (NumberFormatException e) {
//		  e.printStackTrace();
			return false;
		}
	}
	/**
	 * 判断字符串是否是整数
	 */
	public boolean isInteger(String value) {
		try {
			Integer.parseInt(value);
			return true;
		} catch (NumberFormatException e) {
//		  e.printStackTrace();
			return false;
		}
	}
}